package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.DrawNoMapper;
import com.koocloud.electroplatemanage.mapper.IncomePartUnitMapper;
import com.koocloud.electroplatemanage.mapper.OrderNumberMapper;
import com.koocloud.electroplatemanage.pojo.*;
import com.koocloud.electroplatemanage.service.OrderNumberService;
import com.koocloud.electroplatemanage.utils.DeleteFileUtil;
import com.koocloud.electroplatemanage.utils.ExcelUtil;
import com.koocloud.electroplatemanage.utils.StringReplacUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.IncomePartJudgeSqlFieldConstant.*;

/**
 * @program: electroplatemanage
 * @description: 图号服务层实现类
 * @author: zww
 * @create: 2020-11-17 11:13
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class OrderNumberServiceImpl implements OrderNumberService {
    @Resource
    private OrderNumberMapper orderNumberMapper;
    @Resource
    private DrawNoMapper drawNoMapper;
    @Resource
    private IncomePartUnitMapper incomePartUnitMapper;
    Lock lock = new ReentrantLock();
    /**
     *@Description:通过pk查询一条记录
     *@Param: [pk]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate selectByPk(String pk) {
        try {
            //新建订单号实体
            OrderNumberVo orderNumberVo = null;
            orderNumberVo = orderNumberMapper.selectByPk(pk);
            //判断查表操作是否成功
            if (null != orderNumberVo) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(orderNumberVo).build();
            }
            else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }
    /**
     *@Description:查询所有记录 分页
     *@Param: [page, limit]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit,OrderNumberVo orderNumberVo) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                //开始分页
                PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                List<OrderNumberVo> orderNumberVoList = new ArrayList<>();
                //判断模糊查询是否为状态查询 启用为 1 禁用为 0
                if (!StringUtils.isEmpty(orderNumberVo.getIdOrName())){
                    //启用
                    if (STARTUSING.equals(orderNumberVo.getIdOrName())){
                        orderNumberVo.setIdOrName(ONE);
                        orderNumberVoList = orderNumberMapper.selectByDeleteFlag(orderNumberVo);
                    //禁用
                    } else if (FORBIDDEN.equals(orderNumberVo.getIdOrName())){
                        orderNumberVo.setIdOrName(ZERO);
                        orderNumberVoList = orderNumberMapper.selectByDeleteFlag(orderNumberVo);
                    //模糊查询
                    }else {
                        orderNumberVoList = orderNumberMapper.selectAllData(orderNumberVo);
                    }
                }else {
                    //全局查询
                    orderNumberVoList = orderNumberMapper.selectAllData(orderNumberVo);
                }
                //构造分页实体
                PageInfo<OrderNumberVo> info=new PageInfo<>(orderNumberVoList);
                if (info.getTotal()>0) {
                    //查询到数据
                    return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                } else {
                    //没有查询到数据
                    return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }
    
    /**
     *@Description:插入一条记录
     *@Param: [orderNumberVo]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate insert(OrderNumberVo orderNumberVo) {
        try {
            lock.lock();
                //存入图号表
            int rows = orderNumberMapper.insert(orderNumberVo);

            if (rows > 0) {
                return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
            } else {//没有异常并且插入数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }


    /**
     *@Description:逻辑删除一条记录
     *@Param: [pk]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate delete(String pk,String deleteFlag) {
        try {
            lock.lock();
            int rows = orderNumberMapper.delete(pk,deleteFlag);
            //判断删除操作是否成功
            if (rows > 0) {
                //删除成功返回数据
                return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
            }
            else {
                //删除失败返回提示
                return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }

    }

    /**
     *@Description:修改一条记录
     *@Param: [orderNumberVo]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate update(OrderNumberVo orderNumberVo) {
        try {
            lock.lock();
            //没有异常并且修改数据条数大于0
            int rows = orderNumberMapper.update(orderNumberVo);
            if(rows>0) {
                return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 生成订单号
     *@Param:
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate generateOrderNumber() {
        try {
            String orderNumber = "";
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            orderNumber = df.format(date);//获取String类型的时间
            int SerialNumber = orderNumberMapper.selectCurrentOrderNumCount(orderNumber) + 1;
            orderNumber = "PC-"+orderNumber+ SerialNumber;
            return ResponseTemplate.builder().code(0).message("生成订单号成功").data(orderNumber).count(0l).build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.toString()).count(0l).build();
        }

    }
    /**
     *@Description:excel导入
     *@Param: [id, file]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/17
     */
    @Override
    public ResponseTemplate getExcelImport(String file) {
            try {
                lock.lock();
                //获取excel数据
                List<List<String>> excelData = ExcelUtil.getData(file);
                if (excelData.size() == 1 && excelData.get(0).size() == 1){
                    //错误信息
                    String errorInfo = excelData.get(0).get(0);
                    return ResponseTemplate.builder().code(1).message(errorInfo).count(0l).build();
                }
                List<String> headerList = excelData.get(0);

                    List<String> list = new ArrayList<>();
                    for (String str:headerList){
                        //表头
                        list.add(StringReplacUtils.replaceBlank(str));
                    }
                    int count = 0;
                    //抛去表头，从第二行开始
                    for (int i = 1 ; i < excelData.size();i++ ){
                        List<String> listData = excelData.get(i);
                        OrderNumberVo orderNumberVo = new OrderNumberVo();
                        //获取单据编号下标
                        int documentNumberIndex = 0 ;
                        if (list.contains(DOCUMENTNUMBER)){ documentNumberIndex = list.indexOf(DOCUMENTNUMBER); }

                        //获取生产部门下标
                        int generationDepartmentIndex = 0 ;
                        if (list.contains(GENERATIONDEPARTMENT)){ generationDepartmentIndex = list.indexOf(GENERATIONDEPARTMENT); }

                        //获取型号下标
                        int modelNumIndex = 0 ;
                        if (list.contains(MODELNUM)){ modelNumIndex = list.indexOf(MODELNUM); }

                        //获取料品.实体扩展字段.全局段5(料品型别)下标
                        int materialTypeIndex = 0 ;
                        if (list.contains(MATERIALTYPE)){ materialTypeIndex = list.indexOf(MATERIALTYPE); }

                        //获取料号下标
                        int itemNoIndex = 0 ;
                        if (list.contains(ITEMNO)){ itemNoIndex = list.indexOf(ITEMNO); }

                        //获取料品.料品名称下标
                        int materialNameIndex = 0 ;
                        if (list.contains(MATERIALNAME)){ materialNameIndex = list.indexOf(MATERIALNAME); }

                        //判断单据编号是否为空
                        if (StringUtils.isEmpty(listData.get(documentNumberIndex))&&StringUtils.isEmpty(listData.get(itemNoIndex))){
                            continue;
                        }
                        else{
                            if (!StringUtils.isEmpty(listData.get(documentNumberIndex))){
                                orderNumberVo.setOrderNumber(listData.get(documentNumberIndex).trim());
                            }
                            else if (StringUtils.isEmpty(listData.get(documentNumberIndex))&&!StringUtils.isEmpty(listData.get(itemNoIndex))){
                                String orderNumber = "";
                                Date date = new Date();//获取当前的日期
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                                orderNumber = df.format(date);//获取String类型的时间
                                int SerialNumber = orderNumberMapper.selectCurrentOrderNumCount(orderNumber) + 1;
                                orderNumber = "PC-"+orderNumber+ SerialNumber;
                                orderNumberVo.setOrderNumber(orderNumber);
                            }
                        }
                        //根据单据编号查询数据库中的数据
                        OrderNumberVo checkOrderNumberVo = orderNumberMapper.selectByPk(listData.get(documentNumberIndex));


                        //如果存在该单据编号,则不执行插入
                        if (!StringUtils.isEmpty(checkOrderNumberVo)){
                            continue;
                        }

                        //================================================================
                        if(!StringUtils.isEmpty(listData.get(generationDepartmentIndex))){
                            if(!StringUtils.isEmpty(listData.get(generationDepartmentIndex).trim())){
                                //来件单位
                                IncomePartUnitVo incomePartUnitVo = new IncomePartUnitVo();
                                //查询来件单位是否存在
                                IncomePartUnitVo incomePartUnitVoByCnName = incomePartUnitMapper.selectByCnName(listData.get(generationDepartmentIndex).trim());
                                if (!StringUtils.isEmpty(incomePartUnitVoByCnName)){
                                    //存在
                                    orderNumberVo.setIncomePartUnitCode(incomePartUnitVoByCnName.getIncomepartunitCode());
                                }else{
                                    //查询来件单位表中总数
                                    int sum = incomePartUnitMapper.selectAmount();
                                    //获取编号字母的字母下标
                                    int letterGroup = sum/AMOUNT;
                                    //获取编号数字
                                    int numberGroup = sum%AMOUNT;
                                    String str = null;
                                    //字母数组
                                    char[] letters = LETTER.toCharArray();
                                    //判断表中数据为空时和编号数字在0到999之间
                                    if ((letterGroup==0 && numberGroup ==0) || (numberGroup > 0 && numberGroup<AMOUNT)){
                                        str = letters[letterGroup] + String.format("%03d", numberGroup+1);
                                    }else {
                                        str = letters[letterGroup+1] + String.format("%03d", 1);
                                    }
                                    //判断生成的编码是否存在
                                    while(true){
                                        IncomePartUnitVo incomePartUnitVoByCode = incomePartUnitMapper.selectByCode(str);
                                        //存在跳过，继续生成
                                        if (!StringUtils.isEmpty(incomePartUnitVoByCode)){
                                            //字母
                                            String startStr = null;
                                            //数字
                                            String endStr = null;
                                            startStr = str.substring(0,1);
                                            endStr = str.substring(1);
                                            if (Integer.valueOf(endStr) == AMOUNT ){
                                                endStr = String.format("%03d", 1);
                                                if (startStr.equals(letters[letterGroup])){
                                                    startStr = String.valueOf(letters[letterGroup+1]);
                                                }else {
                                                    startStr = String.valueOf(letters[letterGroup+2]);
                                                }
                                                str = startStr + endStr;
                                            }else {
                                                endStr = String.format("%03d", Integer.valueOf(endStr)+1);
                                                str = startStr + endStr;
                                            }
                                        } else {
                                            break;
                                        }
                                    }
                                    incomePartUnitVo.setIncomepartunitCode(str);
                                    incomePartUnitVo.setCnName(listData.get(generationDepartmentIndex).trim());
                                    //存入来件单位表
                                    incomePartUnitMapper.insert(incomePartUnitVo);
                                    //设置来件单位编码
                                    orderNumberVo.setIncomePartUnitCode(str);
                                }
                            }else {
                                orderNumberVo.setIncomePartUnitCode(listData.get(generationDepartmentIndex).trim());
                            }
                        }else {
                            orderNumberVo.setIncomePartUnitCode(listData.get(generationDepartmentIndex));
                        }
                       //================================================================

                        //型号
                        orderNumberVo.setModelNumber(listData.get(modelNumIndex));
                        //型别
                        orderNumberVo.setModelType(listData.get(materialTypeIndex));

                        //================================================================
                        if (!StringUtils.isEmpty(listData.get(itemNoIndex))){
                            if (!StringUtils.isEmpty(listData.get(itemNoIndex).trim())){
                                //图号实体
                                DrawNoVo drawNoVo = new DrawNoVo();
                                //查询图号是否存在
                                DrawNoVo drawNoVoByName = drawNoMapper.selectByName(listData.get(itemNoIndex).trim());
                                if (!StringUtils.isEmpty(drawNoVoByName)) {
                                    //存在
                                    orderNumberVo.setDrawNoCode(drawNoVoByName.getDrawNoCode());
                                }else {
                                    //查询图号表中总数
                                    int sum = drawNoMapper.selectAmount();
                                    //获取编号字母的字母下标
                                    int letterGroup = sum/AMOUNT;
                                    //获取编号数字
                                    int numberGroup = sum%AMOUNT;
                                    String str = null;
                                    //字母数组
                                    char[] letters = LETTER.toCharArray();
                                    //判断表中数据为空时和编号数字在0到999之间
                                    if ((letterGroup==0 && numberGroup ==0) || (numberGroup > 0 && numberGroup<AMOUNT)){
                                        str = letters[letterGroup] + String.format("%03d", numberGroup+1);
                                    }else {
                                        str = letters[letterGroup+1] + String.format("%03d", 1);
                                    }
                                    //判断生成的编码是否存在
                                    while(true){
                                        DrawNoVo drawNoVoByCode = drawNoMapper.selectByCode(str);
                                        //存在跳过，继续生成
                                        if (!StringUtils.isEmpty(drawNoVoByCode)){
                                            //字母
                                            String startStr = null;
                                            //数字
                                            String endStr = null;
                                            startStr = str.substring(0,1);
                                            endStr = str.substring(1);
                                            if (Integer.valueOf(endStr) == AMOUNT ){
                                                endStr = String.format("%03d", 1);
                                                if (startStr.equals(letters[letterGroup])){
                                                    startStr = String.valueOf(letters[letterGroup+1]);
                                                }else {
                                                    startStr = String.valueOf(letters[letterGroup+2]);
                                                }
                                                str = startStr + endStr;
                                            }else {
                                                endStr = String.format("%03d", Integer.valueOf(endStr)+1);
                                                str = startStr + endStr;
                                            }
                                        } else {
                                            break;
                                        }
                                    }
                                    drawNoVo.setDrawNoCode(str);
                                    drawNoVo.setIncomePartUnitCode(orderNumberVo.getIncomePartUnitCode());
                                    drawNoVo.setTypeWorkCode(null);
                                    drawNoVo.setModelNumber(listData.get(modelNumIndex));
                                    drawNoVo.setModelType(listData.get(materialTypeIndex));
                                    drawNoVo.setPartName(listData.get(materialNameIndex));
                                    drawNoVo.setHeatSurfaceSequence(null);
                                    drawNoVo.setName(listData.get(itemNoIndex).trim());
                                    //存入图号表
                                    drawNoMapper.insert(drawNoVo);
                                    //设置图号编码
                                    orderNumberVo.setDrawNoCode(str);
                                }
                            }else {
                                orderNumberVo.setDrawNoCode(listData.get(itemNoIndex).trim());
                            }
                        }else {
                            orderNumberVo.setDrawNoCode(listData.get(itemNoIndex));
                        }

                        //零件名称
                        orderNumberVo.setPartName(listData.get(materialNameIndex));
                        Date date = new Date();//获取当前的日期
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                        String strDate = df.format(date);//获取String类型的时间
                        orderNumberVo.setCreateTime(strDate);
                        orderNumberVo.setDeleteFlag("1");
                        orderNumberVo.setUpdateTime(null);
                        int rows = orderNumberMapper.insert(orderNumberVo);
                        if(rows>0) {
                            count++;
                        }
                    }
                //删除文件
                DeleteFileUtil.delete(file);
                return ResponseTemplate.builder().code(0).message("导入成功").count(Long.valueOf(count)).build();
            } catch (Exception e) {
                e.printStackTrace();
                //事务手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
        }

}